<?php

/**
 * MySQL doesn't really do "prepared" statements so this just mimmicks it.
 * See the MySQLi adaptor for prepared statements.
 * @package Nina
 * @author Chris Corbyn
 */
class Nina_Db_Driver_Statement_Mysql extends Nina_Db_Driver_Statement
{
	/**
	 * The SQL to execute.
	 * @var string
	 */
	protected $sql;
	/**
	 * Bound references.
	 * @var array
	 */
	protected $vars = array();

	/**
	 * Set the SQL to prepare.
	 * @param string $sql SQL
	 */
	public function setSql($sql) {
		$this->sql = $sql;
		$this->prepared = $sql;
	}

	/**
	 * Get the prepared SQL.
	 * @return string
	 */
	public function getSql() {
		return $this->prepare();
	}

	/**
	 * Bind variables to the statement.
	 * Variables are written :varname.
	 * @param Array $vars Variables
	 */
	public function bind(Array $vars) {
		foreach ($vars as $k => &$v) {
			if (!is_int($k)) {
				$k = ":" . $k;
				$this->vars[$k] =& $v;
			}
			else array_push($this->vars, $v);
		}
	}

	/**
	 * Prepare the statement
	 * @return String
	 */
	protected function prepare() {
		$prepared = $this->sql;

		foreach ($this->vars as $k => &$v) {
			if(is_null($v))
				$escaped = 'NULL';
			else
				$escaped = (is_numeric($v) && preg_match('/^[0-9\.]+$/', $v) > 0) ? $v : "'" . str_replace('?', '&#63;', $this->getDb()->escape($v)) . "'";

			if (is_int($k))
				$k = "?";

			$prepared = preg_replace("/" . preg_quote($k) . "/", $escaped, $prepared, 1);
		}

		return str_replace('&#63;', '?', $prepared);
	}

	/**
	 * Execute the statement and return a result.
	 * @return Nina_Db_Adaptor_Result
	 */
	public function execute() {
		return $this->getDb()->query($this->prepare());
	}
}
